﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tuto.Tools;
using Tuto.Objects;
using Npgsql;
namespace Tuto.DAL
{
    /// <summary>
    ///     Author : Tidiane SIDIBE
    ///     Access to the TutoEtudiant informations in the database
    ///     Use the Syngleton pattern
    /// </summary>
    public class TutoEtudiant
    {
        private static Object locker = new Object();
        private static Tuto.DAL.TutoEtudiant _instance = null;
        
        /// <summary>
        ///     Implementation of the Syngleton pattern
        /// </summary>
        public static Tuto.DAL.TutoEtudiant instance
        {
            get
            {
                lock (locker)
                {
                    if (_instance == null)
                        return new TutoEtudiant();
                    else
                        return _instance;
                }
            }
        }
        
        public int addNew(Objects.TutoEtudiant _obj)
        {
            int id = 0;
            NpgsqlConnection conn = DbConnexion.instance.getDbConnection();
            NpgsqlCommand cmd = new NpgsqlCommand();
            
            cmd.CommandText = String.Format
                (
                    "INSERT INTO tuto_etudiant(nom, prenom, adresse, email, telephone, numero_carte, diplome, niveau, date_creation, date_modification) " + 
                    "VALUES({0},{1},{2},{3},{4},{5},{6},{7},{8},{9}",
                    _obj.nom,
                    _obj.prenom,
                    _obj.adresse,
                    _obj.email,
                    _obj.telephone,
                    _obj.numeroCarte,
                    _obj.diplome,
                    _obj.niveau,
                    DateTime.Now.ToLongTimeString(),
                    DateTime.Now.ToLongTimeString()
                );
            try
            {
                cmd.ExecuteNonQuery();

                cmd.CommandText = "SELECT * FROM tuto_etudiant";
                NpgsqlDataReader dReader;
                using (dReader = cmd.ExecuteReader())
                {
                    while (dReader.Read())
                    {
                        //
                    }

                    id = int.Parse(dReader["nom"].ToString());
                }
            }
            catch (Exception e)
            {
                //throw new ApplicationError("Registration failed", e);
                Console.Out.WriteLine(e.Message);
            }
            return id;
        }
    }
}